import { Byte } from '../../api/io/Byte';
import { BattleReportActor } from './BattleReportActor';
import { HashMap } from '../../api/struct/HashMap';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**战报角色属性枚举*/
export const enum E_BattleReportRole {
	/**演员ID*/
	ROLE_ID = 0,
	/**演员信息*/
	ACTOR = 1,
	/**技能*/
	SKILL = 2,
	/**属性*/
	MATH = 3,
	/**枚举数量*/
	EnumCount = 4
}


/**战报角色*/
export class BattleReportRole {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_BATTLE_REPORT_ROLE_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_BATTLE_REPORT_ROLE_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: BattleReportRole[] = [];

	/**创建入口*/
	public static create(json?: string): BattleReportRole {
		const c = this.POOL.pop() || new BattleReportRole();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**演员ID (uint16)*/
	protected _roleId: number;
	/**演员信息*/
	protected _actor: BattleReportActor = null;
	/**技能 (uint32, uint32)*/
	protected _skill: HashMap<number, number> = null;
	/**属性 (uint32)*/
	protected _math: number[] = [];


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (BattleReportRole.POOL.indexOf(this) === -1) {
			BattleReportRole.POOL.push(this);
		}
	}

	/**演员ID*/
	public get roleId() {
		return this._roleId;
	}


	/**演员ID*/
	public set roleId(v: number) {
		this._roleId = v;
	}


	/**演员信息*/
	public get actor() {
		return this._actor;
	}


	/**设置技能*/
	public putSkill(k: number, v: number): number {
		const ov = this._skill.put(k, v);
		return ov || 0;
	}


	/**获取技能*/
	public getSkill(k: number) {
		return this._skill.get(k) || 0;
	}


	/**删除技能*/
	public removeSkill(k: number): number {
		const ov = this._skill.remove(k);
		return ov || 0;
	}


	/**获取技能映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getSkillKeys(): number[] {
		return this._skill.getKeys();
	}


	/**获取技能映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getSkillValues(): number[] {
		return this._skill.getValues();
	}


	/**清空技能映射表*/
	public clearSkillMap(): void {
		this._skill.clear();
	}


	/**增加属性*/
	public addMath(v: number): void {
		if (this._math.indexOf(v) === -1) {
			this._math.push(v);
		}
	}

	/**删除属性*/
	public removeMath(v: number): void {
		const idx = this._math.indexOf(v);
		if (idx >= 0) {
			this._math.splice(idx, 1);
		}
	}

	/**获取属性列表*/
	public getMathList(): number[] {
		return this._math;
	}


	/**通过枚举获取值*/
	public getV(k: E_BattleReportRole): any {
		switch (k) {
			case E_BattleReportRole.ROLE_ID: return this._roleId;
			case E_BattleReportRole.ACTOR: return this._actor;
			case E_BattleReportRole.SKILL: return this._skill;
			case E_BattleReportRole.MATH: return this._math;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_BattleReportRole, v: any): void {
		switch (k) {
			case E_BattleReportRole.ROLE_ID: this._roleId = v; break;
			case E_BattleReportRole.ACTOR: this._actor = v; break;
			case E_BattleReportRole.SKILL: this._skill = v; break;
			case E_BattleReportRole.MATH: this._math = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//演员ID
		this._roleId = 0;
		//演员信息
		if (this._actor) {
			this._actor.destroy();
			this._actor = null;
		}
		if (!fromDestroy) {
			this._actor = BattleReportActor.create();
		}
		//技能
		if (this._skill) {
			this._skill.clear();
		}
		else {
			this._skill = new HashMap<number, number>();
		}
		//属性
		if (this._math) {
			this._math.length = 0;
		}
		else {
			this._math = [];
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._roleId) {
			json.roleId = this._roleId;
		}
		if (this._actor) {
			json.actor = this._actor.stringify(false);
		}
		if (this._skill.size() > 0) {
			const ks = this._skill.getKeys();
			const vs = this._skill.getValues();
			json.skill = [ks, vs];
		}
		if (this._math) {
			json.math = this._math;
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.roleId) {
			this._roleId = json.roleId;
		}
		if (json.actor) {
			this._actor.destroy();
			this._actor = BattleReportActor.create(json.actor);
		}
		if (json.skill) {
			const ks: number[] = json.skill[0];
			const vs: number[] = json.skill[1];
			if (ks && vs && ks.length === vs.length) {	//json
				this._skill.setKeyAndValueList(ks, vs);
			}
			else if (json.skill.getKeys && json.skill.getValues) {	//结构体
				const ks2 = json.skill.getKeys();
				const vs2 = json.skill.getValues();
				if (ks2 && vs2 && ks2.length === vs2.length) {
					for (let i = 0, len = vs2.length; i < len; i++) {
						this._skill.put(ks2[i], vs2[i]);	//重新添加，防止数据公用后被释放导致bug
					}
				}
			}
		}
		if (json.math) {
			this._math = json.math;
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeUint16(this._roleId);
		this._actor.toBytes(byte);
		//技能
		{
			const ks = this._skill.getKeys();
			const vs = this._skill.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint32(ks[i]);
				byte.writeUint32(vs[i]);
			}
		}
		//属性
		{
			const list = this._math;
			if (list) {
				byte.writeUint32(list.length);
				for (let i = 0, len = list.length; i < len; i++) {
					byte.writeUint32(list[i]);
				}
			}
			else {
				byte.writeUint32(0);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._roleId = byte.readUint16();
		this._actor.fromBytes(byte);
		//技能
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint32();
				const v = byte.readUint32();
				this._skill.put(k, v);
			}
		}
		//属性
		{
			const len = byte.readUint32();
			for (let i = 0; i < len; i++) {
				this._math[i] = byte.readUint32();
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): BattleReportRole {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = BattleReportRole.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = BattleReportRole.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//演员ID
			if (idx === E_BattleReportRole.ROLE_ID) {
				const oldv = this._roleId;
				this._roleId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._roleId, oldv);
				i += 2;
				continue;
			}
			//演员信息
			if (idx === E_BattleReportRole.ACTOR) {
				const fui: string = us[i + 1];
				if (this._actor) {
					this._actor.processUpdate(fui);
				}
				else {
					console.error('BattleReportRole actor is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}

			//技能
			if (idx === E_BattleReportRole.SKILL) {
				const k: number = us[i + 1];
				const newv :number = us[i + 2];
				const oldv = this.putSkill(k, newv);
				IAsync.dispatch(eventID, idx, k, newv, oldv);
				i += 3;
				continue;
			}
			//属性
			if (idx === E_BattleReportRole.MATH) {
				const c: number = us[i + 1];
				const v: number = us[i + 2];
				if (c === 0) {
					const idx = this._math.indexOf(v);
					if (idx >= 0) {
						this._math.splice(idx, 1);
					}
				}
				else {
					const idx = this._math.indexOf(v);
					if (idx === -1) {
						this._math.push(v);
					}
				}
				IAsync.dispatch(eventID, idx, c, v);
				i += 3;
				continue;
			}

			console.error('[Struct Data] can not find enum in BattleReportRole with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: BattleReportRole): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._roleId !== other._roleId) {
			updates.push(E_BattleReportRole.ROLE_ID, this._roleId);
		}
		//演员信息
		{
			const ui = this._actor.getCompareInfo(other._actor);
			if (ui && ui.length > 0) {
				updates.push(E_BattleReportRole.ACTOR, ui);
			}
		}

		//技能
		{
			const idx = E_BattleReportRole.SKILL;
			const ks1 = this._skill.getKeys();
			const ks2 = other._skill.getKeys();
			const vs1 = this._skill.getValues();
			const vs2 = other._skill.getValues();
			const rs = MathUtils.intersectSortedArray(ks1, ks2, vs1, vs2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getSkill(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getSkill(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		//属性
		{
			const idx = E_BattleReportRole.MATH;
			const rs = MathUtils.intersectSortedArray(this._math, other._math);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					const oldv = list[i];
					updates.push(idx, 0, oldv);
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(BattleReportRole.TOTAL_EVENT_ID, this.getV(0));
	}

}
